package com.simblog.common.utils;

import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;

import com.simblog.common.ClientParameter;

/**
 * 该类用于对客户端数据进行校验
 * 
 * @author kezhi
 *
 */
public class ClientParameterUtil {

	private static final Logger logger = LoggerFactory.getLogger(ClientParameter.class);
	
	
	private static String processEnv = PropertiesUtil.getString(PropertiesUtil.load("global.properties"), "process.env");

	public static boolean validateSign(Map<String, String> params, ClientParameter clientParameter, String clientSign) {
		if("development".equals(processEnv)){//开发环境，绕过签名验证
			return true;
		}
		
		StringBuffer sb = new StringBuffer();
		// 拼接接口参数
		for (Entry<String, String> entry : params.entrySet()) {
			String value = entry.getValue();
			if (!StringUtils.isBlank(value) && !value.trim().equals("null")) {
				sb.append(entry.getKey() + entry.getValue());
			}
		}
		// 接口参数+固定参数
		sb.append(clientParameter.getSpliceParameter());
		logger.info("客户端接口签名：" + clientSign);
		logger.info("客户端接口参数：" + sb.toString());
		String md5Str = MD5Util.getMD5(sb.toString());
		logger.info("接口参数签名：" + md5Str);

		// 判断参数是否为空
		if (StringUtils.isEmpty(md5Str) || StringUtils.isEmpty(clientSign)) {
			return false;
		}

		// 判断签名是否相等
		if (!md5Str.equals(clientSign)) {
			return false;
		}
		return true;
	}

}
